<template>
  <div class="fullscreen-container">
    <div class="problem-layout">
      <!-- 左侧题目详情 -->
      <div class="problem-info" :class="{ 'collapsed': editorFullscreen }">
        <div class="problem-card" v-loading="loading">
          <div class="problem-header">
            <div class="title-wrapper">
              <span class="title">{{ problem?.title || '加载中...' }}</span>
              <el-tag v-if="problem" :type="getDifficultyType(problem.difficulty)" size="large">
                {{ formatDifficulty(problem.difficulty) }}
              </el-tag>
            </div>
            <div class="header-actions">
              <el-button type="text" @click="activeTab = 'content'">题目</el-button>
              <el-button type="text" @click="activeTab = 'comments'">评论</el-button>
              <el-button type="text" @click="toggleEditorSize">
                {{ editorFullscreen ? '显示题目' : '隐藏题目' }}
                <el-icon class="ml-2"><ArrowRight v-if="editorFullscreen" /><ArrowLeft v-else /></el-icon>
              </el-button>
            </div>
          </div>
          <div v-if="activeTab === 'content'">
            <div v-if="problem" class="problem-content">
              <!-- 题目信息 -->
              <div class="info-row">
                <el-tag v-for="tag in formatTags(problem.tag)" :key="tag" class="tag-item" effect="plain">
                  {{ tag }}
                </el-tag>
              </div>
              <!-- 题目描述 -->
              <div class="section">
                <h3 class="section-title">题目描述</h3>
                <p class="section-content">{{ problem.content }}</p>
              </div>
              <!-- 限制信息 -->
              <div class="section constraints-section">
                <h3 class="section-title">限制条件</h3>
                <div class="constraints-list">
                  <div class="constraint-item">
                    <span class="constraint-label">时间限制:</span>
                    <span class="constraint-value">{{ formatTimeLimit(problem.timeLimit) }}</span>
                  </div>
                  <div class="constraint-item">
                    <span class="constraint-label">内存限制:</span>
                    <span class="constraint-value">{{ formatMemoryLimit(problem.memoryLimit) }}</span>
                  </div>
                </div>
              </div>
              <!-- 示例 -->
              <div class="section">
                <h3 class="section-title">示例</h3>
                <div v-if="examples.length > 0" class="examples-container">
                  <div v-for="(example, index) in examples" :key="index" class="example-item">
                    <div class="example-header">示例 {{ index + 1 }}</div>
                    <div class="example-content">
                      <div class="example-row">
                        <div class="example-input">
                          <div class="example-label">输入:</div>
                          <div class="input-line">{{ example.input }}</div>
                        </div>
                        <div class="example-output">
                          <div class="example-label">输出:</div>
                          <div class="output-line">{{ example.output }}</div>
                        </div>
                      </div>
                    </div>
                  </div>
                </div>
              </div>
            </div>
            <div v-else-if="!loading" class="error-message">
              无法加载题目详情，请稍后再试或返回题目列表页面。
            </div>
          </div>
          <div v-else-if="activeTab === 'comments'">
            <ProblemComments :problemId="problemId" />
          </div>
        </div>
      </div>
      
      <!-- 右侧代码编辑器 -->
      <div class="code-editor-container" :class="{ 'fullscreen': editorFullscreen }">
        <div class="editor-header">
          <div class="code-title">
            <span>{{ problem?.title || '代码编辑区' }}</span>
            <span class="problem-id">题目ID: {{ problemId }}</span>
          </div>
          <div class="language-selector">
            <el-select v-model="selectedLanguage" placeholder="选择语言" size="small" @change="resetCode">
              <el-option v-for="lang in languages" :key="lang.value" :label="lang.label" :value="lang.value" />
            </el-select>
          </div>
        </div>
        
        <div class="editor-area">
          <textarea
            v-model="code"
            class="code-textarea"
            placeholder="在这里编写你的代码..."
            spellcheck="false"
            @keydown.tab.prevent="handleTab"
          ></textarea>
        </div>
        
        <div class="editor-footer">
          <div class="actions">
            <el-button type="primary" @click="submitCode" :loading="submitting">
              提交代码
            </el-button>
            <el-button @click="resetCode">
              重置
            </el-button>
          </div>
          
          <!-- 结果展示区域 -->
          <div v-if="result" class="result-container">
            <div class="result-header" :class="getResultClass(result.status)">
              运行结果: {{ formatStatus(result.status) }}
            </div>
            <div class="result-details">
              <div v-if="result.time" class="result-item">
                <span class="result-label">执行时间:</span>
                <span>{{ result.time }} ms</span>
              </div>
              <div v-if="result.memory" class="result-item">
                <span class="result-label">内存消耗:</span>
                <span>{{ result.memory }} KB</span>
              </div>
              <div v-if="result.message" class="result-message">
                <span class="result-label">输出信息:</span>
                <pre>{{ result.message }}</pre>
              </div>
            </div>
          </div>
        </div>
      </div>
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, onMounted, computed, onBeforeMount, nextTick } from 'vue';
import { useRoute, useRouter } from 'vue-router';
import { ElMessage } from 'element-plus';
import { ArrowLeft, ArrowRight } from '@element-plus/icons-vue';
import { getProblemDetail, saveUserRecord } from '../api/problem';
import { useUserStore } from '../store/user';
import ProblemComments from './ProblemComments.vue';

const activeTab = ref<'content' | 'comments'>('content');

// 路由信息获取
const route = useRoute();
const router = useRouter();
const problemId = computed(() => {
  const id = Number(route.params.id);
  return isNaN(id) ? null : id;
});

// 数据状态
const problem = ref<any>(null);
const loading = ref(true);
const editorFullscreen = ref(false);

// 代码编辑器状态
const code = ref('');
const selectedLanguage = ref('java');
const submitting = ref(false);
const result = ref<any>(null);

// 编程语言选项
const languages = [
  { label: 'Java', value: 'java' },
  { label: 'C++', value: 'cpp' },
  { label: 'Python', value: 'python' }
];

// 处理Tab键
const handleTab = (e: KeyboardEvent) => {
  const textarea = e.target as HTMLTextAreaElement;
  const start = textarea.selectionStart;
  const end = textarea.selectionEnd;
  
  // 插入两个空格作为缩进
  code.value = code.value.substring(0, start) + '  ' + code.value.substring(end);
  
  // 在下一个事件循环中设置光标位置
  nextTick(() => {
    textarea.selectionStart = textarea.selectionEnd = start + 2;
  });
};

// 切换编辑器显示模式
const toggleEditorSize = () => {
  editorFullscreen.value = !editorFullscreen.value;
};

// 默认代码模板
const getDefaultCode = (language: string) => {
  switch (language) {
    case 'java':
      return `class Solution {
    public int[] twoSum(int[] nums, int target) {
        // 在这里编写你的代码
        return null;
    }
}`;
    case 'cpp':
      return `class Solution {
public:
    vector<int> twoSum(vector<int>& nums, int target) {
        // 在这里编写你的代码
        return {};
    }
};`;
    case 'python':
      return `class Solution:
    def twoSum(self, nums, target):
        # 在这里编写你的代码
        pass`;
    default:
      return '';
  }
};

// 监听语言变化设置默认代码
const resetCode = () => {
  code.value = getDefaultCode(selectedLanguage.value);
};

// 解析示例输入输出
const examples = computed(() => {
  if (!problem.value) return [];
  
  try {
    const exampleIn = JSON.parse(problem.value.exampleCin || '{}');
    const exampleOut = JSON.parse(problem.value.exampleOut || '{}');
    
    // 将输入输出配对，简化展示格式
    const result = [];
    for (const key in exampleIn) {
      if (exampleOut.hasOwnProperty(key.replace('in', 'out'))) {
        const outKey = key.replace('in', 'out');
        
        // 将输入和输出都格式化为单行
        const inputValue = Array.isArray(exampleIn[key]) ? 
                JSON.stringify(exampleIn[key]) : 
                JSON.stringify(exampleIn[key]);
        
        const outputValue = Array.isArray(exampleOut[outKey]) ? 
                  JSON.stringify(exampleOut[outKey]) : 
                  JSON.stringify(exampleOut[outKey]);
        
        result.push({
          input: inputValue,
          output: outputValue
        });
      }
    }
    
    return result;
  } catch (error) {
    console.error('解析示例数据失败:', error);
    return [];
  }
});

// 格式化时间限制
const formatTimeLimit = (nanoseconds: number) => {
  if (!nanoseconds) return '未知';
  const milliseconds = nanoseconds / 1000000;
  if (milliseconds >= 1000) {
    return `${milliseconds / 1000} 秒`;
  }
  return `${milliseconds} 毫秒`;
};

// 格式化内存限制
const formatMemoryLimit = (bytes: number) => {
  if (!bytes) return '未知';
  const megabytes = bytes / (1024 * 1024);
  return `${megabytes} MB`;
};

// 格式化难度
const formatDifficulty = (difficulty: number | string) => {
  if (difficulty === 0 || difficulty === '0') return '简单';
  if (difficulty === 1 || difficulty === '1') return '中等';
  if (difficulty === 2 || difficulty === '2') return '困难';
  return '未知';
};

// 获取难度标签类型
const getDifficultyType = (difficulty: number | string) => {
  if (difficulty === 0 || difficulty === '0') return 'success';
  if (difficulty === 1 || difficulty === '1') return 'warning';
  if (difficulty === 2 || difficulty === '2') return 'danger';
  return 'info';
};

// 格式化标签
const formatTags = (tags: string) => {
  if (!tags) return [];
  return tags.split(',').filter(tag => tag.trim());
};

// 获取题目详情
const fetchProblemDetail = async () => {
  if (!problemId.value) {
    ElMessage.error('无效的题目ID');
    router.push('/problems');
    return;
  }
  
  loading.value = true;
  try {
    const result = await getProblemDetail(problemId.value);
    problem.value = result.data;
    // 初始化代码编辑器
    resetCode();
  } catch (error) {
    ElMessage.error('获取题目详情失败');
    console.error('获取题目详情失败:', error);
  } finally {
    loading.value = false;
  }
};

// 提交代码
const submitCode = async () => {
  if (!problemId.value) {
    ElMessage.error('无效的题目ID');
    return;
  }
  
  if (!code.value.trim()) {
    ElMessage.warning('请先编写代码');
    return;
  }
  
  submitting.value = true;
  try {
    // 调用实际的评测接口
    ElMessage.info('已提交代码，评测中...');
    
    const judgeInput = {
      code: code.value,
      language: selectedLanguage.value,
      pid: problemId.value
    };

    // 获取用户认证信息
    const userStore = useUserStore();

    // 使用fetch API发送请求
    const response = await fetch('/api/judge', {
      method: 'POST',
      headers: {
        'Content-Type': 'application/json',
        'token': userStore.token || ''
      },
      body: JSON.stringify(judgeInput),
      credentials: 'include'
    });

    const responseData = await response.json();
    
    if (responseData.code !== 0) {
      throw new Error(responseData.msg || '评测失败');
    }
    
    // 处理评测结果
    result.value = {
      status: responseData.data.status || 'Unknown',
      time: responseData.data.time,
      memory: responseData.data.memory,
      message: responseData.data.message || responseData.data.output || ''
    };

    // 保存用户记录
    if (userStore.userInfo?.id && responseData.data.status) {
      try {
        await saveUserRecord({
          uid: userStore.userInfo.id,
          pid: problemId.value!,
          massage: responseData.data.message || responseData.data.output || '',
          runtime: responseData.data.time || 0,
          memory: responseData.data.memory || 0,
          code: code.value,
          language: selectedLanguage.value
        });
      } catch (saveError) {
        console.error('保存做题记录失败:', saveError);
      }
    }

  } catch (error: any) {
    ElMessage.error('提交代码失败: ' + (error.message || '未知错误'));
    console.error('提交代码失败:', error);
  } finally {
    submitting.value = false;
  }
};

// 格式化评测状态
const formatStatus = (status: string) => {
  const statusMap: Record<string, string> = {
    'AC': '通过',
    'WA': '答案错误',
    'TLE': '超时',
    'MLE': '内存超限',
    'RE': '运行错误',
    'CE': '编译错误'
  };
  return statusMap[status] || status;
};

// 获取结果类名
const getResultClass = (status: string) => {
  const classMap: Record<string, string> = {
    'AC': 'success',
    'WA': 'error',
    'TLE': 'warning',
    'MLE': 'warning',
    'RE': 'error',
    'CE': 'error'
  };
  return classMap[status] || '';
};

// 设置布局高度
const setFullHeight = () => {
  const vh = window.innerHeight;
  document.documentElement.style.setProperty('--vh', `${vh}px`);
};

onBeforeMount(() => {
  setFullHeight();
  window.addEventListener('resize', setFullHeight);
});

onMounted(() => {
  fetchProblemDetail();
});
</script>

<style scoped lang="scss">
/* 全局样式变量 */
:root {
  --editor-bg-color: #121212; /* 更深的黑色 */
  --editor-text-color: #d4d4d4;
  --header-bg-color: #1e1e1e;
  --header-text-color: #cccccc;
  --footer-bg-color: #1e1e1e;
  --border-color: #333;
  --highlight-color: #007acc;
}

.fullscreen-container {
  position: fixed;
  top: 60px; /* 导航栏高度 */
  left: 0;
  right: 0;
  bottom: 0;
  z-index: 100;
  display: flex;
  overflow: hidden;
  background-color: #f5f7fa;
}

.problem-layout {
  display: flex;
  width: 100%;
  height: 100%;
  
  @media (max-width: 1200px) {
    flex-direction: column;
  }
}

/* 左侧题目信息区 */
.problem-info {
  width: 40%;
  height: 100%;
  transition: all 0.3s ease;
  overflow: auto;
  background-color: #fff;
  border-right: 1px solid #e4e7ed;
  
  &.collapsed {
    width: 0;
    overflow: hidden;
  }
}

.problem-card {
  height: 100%;
  display: flex;
  flex-direction: column;
  padding: 0;
}

.problem-header {
  padding: 16px;
  display: flex;
  align-items: center;
  justify-content: space-between;
  border-bottom: 1px solid #e4e7ed;
  background-color: #f5f7fa;
  
  .title-wrapper {
    display: flex;
    align-items: center;
    gap: 12px;
    
    .title {
      font-size: 18px;
      font-weight: bold;
    }
  }
  
  .header-actions {
    display: flex;
    gap: 8px;
  }
}

.ml-2 {
  margin-left: 4px;
}

.problem-content {
  padding: 16px;
  overflow-y: auto;
  flex: 1;
}

/* 右侧代码编辑器区 */
.code-editor-container {
  flex: 1;
  display: flex;
  flex-direction: column;
  height: 100%;
  overflow: hidden;
  background-color: var(--editor-bg-color);
  transition: all 0.3s ease;
  
  &.fullscreen {
    width: 100%;
  }
}

.editor-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 12px 16px;
  background-color: var(--header-bg-color);
  border-bottom: 1px solid var(--border-color);
  color: var(--header-text-color);
}

.code-title {
  display: flex;
  align-items: center;
  gap: 12px;
  
  .problem-id {
    font-size: 14px;
    color: #8c8c8c;
  }
}

.language-selector {
  min-width: 120px;
}

.editor-area {
  flex: 1;
  overflow: hidden;
  position: relative;
}

.code-textarea {
  width: 100%;
  height: 100%;
  padding: 16px;
  font-family: 'Consolas', 'Monaco', 'Courier New', monospace;
  font-size: 15px;
  line-height: 1.6;
  color: var(--editor-text-color);
  background-color: var(--editor-bg-color) !important; /* 强制应用黑色背景 */
  border: none;
  resize: none;
  outline: none;
  tab-size: 4;
  
  &::placeholder {
    color: #666;
  }
}

.editor-footer {
  padding: 16px;
  background-color: var(--footer-bg-color);
  border-top: 1px solid var(--border-color);
  color: var(--header-text-color);
}

.actions {
  display: flex;
  gap: 12px;
  margin-bottom: 16px;
}

.result-container {
  border: 1px solid #444;
  border-radius: 4px;
  overflow: hidden;
  background-color: #2d2d2d;
}

.result-header {
  padding: 10px 15px;
  font-weight: bold;
  
  &.success {
    background-color: rgba(103, 194, 58, 0.2);
    color: #67c23a;
  }
  
  &.error {
    background-color: rgba(245, 108, 108, 0.2);
    color: #f56c6c;
  }
  
  &.warning {
    background-color: rgba(230, 162, 60, 0.2);
    color: #e6a23c;
  }
}

.result-details {
  padding: 15px;
}

.result-item {
  margin-bottom: 8px;
}

.result-label {
  font-weight: 500;
  margin-right: 8px;
}

.result-message {
  margin-top: 12px;
  
  pre {
    margin-top: 8px;
    padding: 10px;
    background-color: #1a1a1a;
    border-radius: 4px;
    color: #ddd;
    white-space: pre-wrap;
    word-break: break-all;
  }
}

/* 题目内容样式 */
.info-row {
  margin: 8px 0 16px;
  display: flex;
  flex-wrap: wrap;
  gap: 8px;
}

.tag-item {
  margin-right: 0;
}

.section {
  margin-bottom: 20px;
  
  .section-title {
    margin-bottom: 12px;
    font-size: 16px;
    font-weight: bold;
    border-bottom: 1px solid #eee;
    padding-bottom: 8px;
    color: #333;
  }
  
  .section-content {
    line-height: 1.6;
    white-space: pre-wrap;
    margin: 0;
    color: #303133;
  }
}

.constraints-section {
  margin-bottom: 20px;
}

.constraints-list {
  display: flex;
  flex-wrap: wrap;
  gap: 16px;
}

.constraint-item {
  display: flex;
  align-items: center;
  
  .constraint-label {
    font-weight: 500;
    margin-right: 6px;
    color: #606266;
  }
  
  .constraint-value {
    color: #303133;
    font-family: 'Courier New', Courier, monospace;
  }
}

.examples-container {
  display: flex;
  flex-direction: column;
  gap: 16px;
}

.example-item {
  border: 1px solid #eaeaea;
  border-radius: 6px;
  overflow: hidden;
}

.example-header {
  background-color: #f5f7fa;
  padding: 8px 12px;
  font-weight: 500;
  font-size: 14px;
  color: #606266;
}

.example-content {
  padding: 12px;
}

.example-row {
  display: flex;
  flex-direction: column;
  gap: 16px;
  
  @media (min-width: 768px) {
    flex-direction: row;
  }
}

.example-input,
.example-output {
  flex: 1;
  min-width: 0;
}

.example-label {
  font-weight: 500;
  margin-bottom: 6px;
  color: #606266;
  font-size: 14px;
}

.input-line, .output-line {
  background-color: #f9f9f9;
  padding: 10px;
  border-radius: 4px;
  font-family: 'Consolas', 'Monaco', 'Courier New', monospace;
  white-space: nowrap;
  overflow-x: auto;
  color: #303133;
  font-size: 13px;
}

pre {
  background-color: #f9f9f9;
  padding: 10px;
  border-radius: 4px;
  overflow-x: auto;
  font-family: 'Consolas', 'Monaco', 'Courier New', monospace;
  margin: 0;
  white-space: pre-wrap;
  word-break: break-word;
  font-size: 13px;
  color: #303133;
}

.error-message {
  text-align: center;
  color: #f56c6c;
  padding: 20px;
}
</style>
